package com.cloudcc.mobile.view.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.AttendanceEntity;
import com.cloudcc.mobile.event.AttendanceEventList.AttendanceHomeEvent;
import com.cloudcc.mobile.event.AttendanceEventList.CheckResultEvent;
import com.cloudcc.mobile.manager.LocationManager;
import com.cloudcc.mobile.presenter.AttendancePresenter;
import com.cloudcc.mobile.presenter.AttendancePresenter.AttendanceHomeEntity;
import com.cloudcc.mobile.util.PopuWindowUtils;
import com.cloudcc.mobile.util.ViewUtils;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.weight.DialogUtils;
import com.cloudcc.mobile.weight.DialogUtils.DialogOnClickListener;
import com.cloudcc.mobile.widget.fancybuttons.FancyButton;

public class AttendanceMainFragment extends BaseFragment {
	/**
	 * 内勤
	 */
	private static final int TYPE_INNER = 1;
	/**
	 * 外勤
	 */
	private static final int TYPE_OUTTER = 2;

	private static final int OPS_CHECK_LOGIN = 1;// 操作 签到

	private static final int OPS_CHECK_LOGINOUT = 2;// 签退

	private static final int OPS_LOC = 3;// 定位
	@Bind(R.id.indexselect)
	RelativeLayout indexselect;// 上面的选择框
	@Bind(R.id.textView1)
	TextView title;

	// 标题
	@Bind(R.id.attendance_title)
	TextView attendance_title;

	@Bind(R.id.attendance_time)
	TextView attendance_time;

	@Bind(R.id.attendance_location)
	TextView attendance_location;
	@Bind(R.id.attendance_qt_title)
	TextView attendance_qt_title;
	@Bind(R.id.attendance_qt_time)
	TextView attendance_qt_time;
	@Bind(R.id.attendance_qt_location)
	TextView attendance_qt_location;
	@Bind(R.id.attendance_now)
	TextView attendance_now;

	@Bind(R.id.attendance_qd_check)
	FancyButton btn_checkIn;

	private int attendanceTypeIndex = 1;// 默认是 内勤

	private int mCurrentOpsIndex = -1;

	private AttendancePresenter mAttendancePresenter = new AttendancePresenter();

	private AttendanceHomeEntity mHomeEntity;

	@Override
	public void init() {
		super.init();
		showWainting();
		refreshHome();
	}

	private void refreshHome() {
		mAttendancePresenter.queryHome();
	}

	@OnClick(R.id.indexselect)
	public void onClickIndex() {
		showWindow();
	}

	@OnClick(R.id.attendance_qd_check)
	public void onClickCheckIn() {
		// #1 看看有位置吗 没有的话 定位啊
		mCurrentOpsIndex = OPS_CHECK_LOGIN;
		if (null == lastDBLocation) {// 无定位数据 先去定位

			startLocal(true);
		} else {
			showCheckInResult();
		}
	}

	@OnClick(R.id.attendance_qd_out)
	public void onClickOut() {
		// 签退
		mCurrentOpsIndex = OPS_CHECK_LOGINOUT;
		if (null == lastDBLocation) {
			startLocal(true);
		} else {// 已经存在定位数据
			showCheckOutResult();
		}
	}

	@OnClick(R.id.attendance_qd_location)
	public void onClickLoc() {
		mCurrentOpsIndex = OPS_LOC;
		startLocal(true);
	}

	public void onEventMainThread(CheckResultEvent event) {
		String ops = "签";
		if (mCurrentOpsIndex == OPS_CHECK_LOGIN) {
			ops += "到";
		} else {
			ops += "退";
		}
		dismissWainting();
		if (event.isError()) {
			showToast(ops + "失败(" + event.getMessage() + ")");
			return;
		}
		showToast(ops + "成功");
		refreshHome();

	}

	public void onEventMainThread(AttendanceHomeEvent event) {
		dismissWainting();
		if (event.isError()) {
			showToast("初始化失败。。。");
			getActivity().finish();
			return;
		}
		mHomeEntity = event.getData();

		fillUI();

	}

	/**
	 * 今天是否已经签到
	 * 
	 * @return 2016-4-29
	 */
	private boolean hasCheckInToday() {
		if (null != mHomeEntity && mHomeEntity.todaycheck != null
				&& StringUtils.isNotBlank(mHomeEntity.todaycheck.qdsj))
			return true;
		return false;
	}

	private void fillUI() {
		if (null == mHomeEntity || mHomeEntity.todaycheck == null) {
			return;
		}
		AttendanceEntity todaycheck = mHomeEntity.todaycheck;

		ViewUtils.setText(attendance_now, todaycheck.rq);

		ViewUtils.setText(attendance_title, hasCheckIn() ? "已签到" : "未签到");
		ViewUtils.setText(attendance_time, todaycheck.qdsj);
		ViewUtils.setText(attendance_location, todaycheck.qdwz);

		ViewUtils.setText(attendance_qt_title, hasCheckOut() ? "已签退" : "未签退");
		ViewUtils.setText(attendance_qt_time, todaycheck.qtsj);
		ViewUtils.setText(attendance_qt_location, todaycheck.qtwz);
		
		
		//
		if (hasCheckInToday()) {
			btn_checkIn.setBackgroundColor(mContext.getResources().getColor(R.color.gray_pressed));
			btn_checkIn.setEnabled(false);
		}else{
			btn_checkIn.setBackgroundColor(Color.parseColor("#55acee"));
			btn_checkIn.setEnabled(true);
		}
	}

	/**
	 * 是否已经签到
	 * 
	 * @return
	 */
	private boolean hasCheckIn() {
		if (null == mHomeEntity
				|| mHomeEntity.todaycheck == null
				|| (StringUtils.isBlank(mHomeEntity.todaycheck.qdsj) && StringUtils
						.isBlank(mHomeEntity.todaycheck.qdzb)))
			return false;
		return true;
	}

	/**
	 * 是否已经签退
	 * 
	 * @return 已经签退
	 */
	private boolean hasCheckOut() {
		if (null == mHomeEntity
				|| mHomeEntity.todaycheck == null
				|| (StringUtils.isBlank(mHomeEntity.todaycheck.qtsj) && StringUtils
						.isBlank(mHomeEntity.todaycheck.qtzb)))
			return false;
		return true;
	}

	/**
	 * 签到或者签退
	 */
	private void check(int checkInOrOut) {
		showWainting();
		if (null == lastDBLocation) {
			dismissWainting();
			showToast("请重新定位...");
			return;
		}

		// 非空 判断
		if (null == mHomeEntity || null == mHomeEntity.checkloc) {
			dismissWainting();
			showToast("参数错误...");
			return;
		}

		int userAttTypeNumber = getUserAttTypeNumber();
		if (userAttTypeNumber == 1) {// 内勤外勤都能签到
			checkToNet(checkInOrOut);
		} else if (userAttTypeNumber == 2) {// 只能签到外勤
			if (attendanceTypeIndex == TYPE_INNER) {
				dismissWainting();
				showToast("对不起,当前只允许你签到外勤...");
			} else {
				checkToNet(checkInOrOut);
			}
		} else if (userAttTypeNumber == 3) {// 存在坐标点
			/*
			 * 1、内勤用户 签到 内勤 判断距离 签到外勤 不用判断距离 2、外勤用户 签到 内勤 判断距离 签到外勤 判断距离
			 */
			if (2 == mHomeEntity.checkloc.type) {// 外勤用户
				// 判断距离
				boolean inCenter = isInCenter();
				if (inCenter) {
					checkToNet(checkInOrOut);
				}
			} else if (1 == mHomeEntity.checkloc.type) {// 内勤用户
				if (attendanceTypeIndex == TYPE_INNER) {
					boolean inCenter = isInCenter();
					if (inCenter) {
						checkToNet(checkInOrOut);
					}
				} else {
					checkToNet(checkInOrOut);
				}
			}

		}
	}

	/**
	 * 是否满足 在 坐标点范围内
	 * 
	 * @param disNow
	 * @return 2016-4-27
	 */
	private boolean isInCenter() {
		if (mHomeEntity.checkloc.deviation <= 0) {
			mHomeEntity.checkloc.deviation = 200;
		}

		int betweenCenter = distanceBetweenCenter();

		if (mHomeEntity.checkloc.deviation < betweenCenter) {
			dismissWainting();
			showToast("不允许签到,相差:" + String.valueOf((int) betweenCenter));
			return false;
		}
		return true;

	}

	/**
	 * 计算
	 * 
	 * @return 2016-4-27
	 */
	private int distanceBetweenCenter() {

		if (lastDBLocation == null || mHomeEntity.checkloc.lat <= 0
				|| mHomeEntity.checkloc.lon <= 0) {
			return -1;
		}

		LatLng latlngMy = new LatLng(lastDBLocation.getLatitude(),
				lastDBLocation.getLongitude());
		LatLng latlngCenter = new LatLng(mHomeEntity.checkloc.lat,
				mHomeEntity.checkloc.lon);

		double distance = DistanceUtil.getDistance(latlngMy, latlngCenter);
		return (int) distance;
	}

	/**
	 * 签到签退
	 * 
	 * @param checkInOrOut
	 *            2016-4-27
	 */
	private void checkToNet(int checkInOrOut) {
		String addr = LocationManager.getDetailAddr(lastDBLocation, false);
		mAttendancePresenter.check(
				String.valueOf(lastDBLocation.getLongitude()),
				String.valueOf(lastDBLocation.getLatitude()),
				String.valueOf(attendanceTypeIndex), addr, checkInOrOut);
	}

	/**
	 * 获得当前用户的签到类型
	 * 
	 * @return 1 :-1类型 <br>
	 *         2:null<br>
	 *         3:有坐标点 2016-4-27
	 */
	private int getUserAttTypeNumber() {

		if (null == mHomeEntity || mHomeEntity.checkloc == null) {
			return -1;// 还没有获取到 今日的签到信息
		}
		if (mHomeEntity.checkloc.lat == 0.0 || mHomeEntity.checkloc.lon == 0.0) {
			return 2;
		}
		if (mHomeEntity.checkloc.lat < 0 || mHomeEntity.checkloc.lon < 0) {
			return 1;
		}
		if (mHomeEntity.checkloc.lat > 0 && mHomeEntity.checkloc.lon > 00) {
			return 3;
		}
		return 0;
	}

	/**
	 * 服务器是否配置了签到中心点
	 * 
	 * @return 2016-3-30
	 */
	private boolean hasCheckCenter() {
		return null != mHomeEntity && null != mHomeEntity.checkloc
				&& mHomeEntity.checkloc.lat > 0 && mHomeEntity.checkloc.lon > 0;
	}

	private boolean shouldShowWaiting = false;// 是否显示dialog 在定位的时候

	/**
	 * 开始定位
	 * 
	 * @param isShowWaiting
	 *            是否显示 定位进行的时候的dialog 提示
	 */
	private void startLocal(boolean isShowWaiting) {
		shouldShowWaiting = isShowWaiting;
		if (isShowWaiting) {// 显示定位的等待提示
			showWainting("正在定位,请稍等...");
		}
		LocationManager.getInstance().registerListener(mListener);
		LocationManager.getInstance().requestLocal();
	}

	/**
	 * 定位结束的时候
	 * 
	 * @param success
	 *            是否定位成功
	 */
	private void onLocalFinish(boolean success) {
		if (shouldShowWaiting) {// 刚才显示dialog 了 取消吊
			dismissWainting();
		}
		if (!success) {
			showToast("定位失败,请重试");
			return;
		}
		switch (mCurrentOpsIndex) {
		case 1:// 签到
			showCheckInResult();
			break;
		case 2:// 签退
			showCheckOutResult();
			break;
		case 3:// 定位
			showLocResult();
			break;

		}
	}

	/**
	 * 显示点击显示的结果 2016-4-22
	 */
	private void showCheckInResult() {
		showLocalResult(new DialogOnClickListener() {
			@Override
			public void onClickPositive(Dialog dialog) {
				dialog.cancel();
				check(1);
			}

			@Override
			public void onClickNegative(Dialog dialog) {
				dialog.cancel();
			}
		});
	}

	private void showCheckOutResult() {
		showLocalResult(new DialogOnClickListener() {
			@Override
			public void onClickPositive(Dialog dialog) {
				dialog.cancel();
				check(2);
			}

			@Override
			public void onClickNegative(Dialog dialog) {
				dialog.cancel();
			}
		});
	}

	private void showLocResult() {
		showLocalResult(new DialogOnClickListener() {
			@Override
			public void onClickPositive(Dialog dialog) {
				dialog.cancel();
			}

			@Override
			public void onClickNegative(Dialog dialog) {
				dialog.cancel();
			}
		});
	}

	/**
	 * 显示 当前位置dialog
	 */
	private void showLocalResult(DialogOnClickListener l) {
		String addr = LocationManager.getDetailAddr(lastDBLocation, true);

		// 计算 距离
		String distanceStr = "";
		if (null != lastDBLocation
				&& hasCheckCenter()
				&& (!(attendanceTypeIndex == TYPE_OUTTER && mHomeEntity.checkloc.type == 1))) {// 存在坐标点
																								// 的时候才显示
																								// 距离
			LatLng lastLatLng = new LatLng(lastDBLocation.getLatitude(),
					lastDBLocation.getLongitude());
			LatLng latLng = new LatLng(mHomeEntity.checkloc.lat,
					mHomeEntity.checkloc.lon);
			double distance = DistanceUtil.getDistance(lastLatLng, latLng);
			distanceStr = "距离签到点:" + String.valueOf((int) distance) + "m";
		}

		if (TextUtils.isEmpty(addr)) {
			return;
		}
		String message = addr + "\n" + distanceStr;
		try {
			DialogUtils.showWarn(mContext, "提示", message, l);
		} catch (Exception e) {
		}
	}

	private PopupWindow attendanceType;

	private void showWindow() {
		PopuWindowUtils.dissmiss(attendanceType);
		RadioGroup group = (RadioGroup) LayoutInflater.from(getActivity())
				.inflate(R.layout.attendance_type_pop, null);
		WindowManager wm = getActivity().getWindowManager();
		int width = wm.getDefaultDisplay().getWidth() / 2;
		attendanceType = new PopupWindow(group, width,
				LayoutParams.WRAP_CONTENT);
		attendanceType.setFocusable(true);
		attendanceType.setOutsideTouchable(true);
		attendanceType.setBackgroundDrawable(new ColorDrawable(
				Color.TRANSPARENT));

		int xPos = indexselect.getWidth() / 2 - attendanceType.getWidth() / 2;
		attendanceType.showAsDropDown(indexselect, xPos, 12);
		group.check(attendanceTypeIndex == 1 ? R.id.attendance_type_in
				: R.id.attendance_type_out);
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup arg0, int checkId) {

				if (checkId == R.id.attendance_type_in) {
					attendanceTypeIndex = TYPE_INNER;
				} else {
					attendanceTypeIndex = TYPE_OUTTER;

				}
				PopuWindowUtils.dissmiss(attendanceType);
				RadioButton rbN = (RadioButton) arg0.findViewById(checkId);
				title.setText(rbN.getText());
			}
		});
	}

	private BDLocation lastDBLocation;// 最新的定位位置
	private BDLocationListener mListener = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (null != location
					&& location.getLocType() != BDLocation.TypeServerError) {
				lastDBLocation = location;
				LocationManager.getInstance().stopRequestLocal();
				LocationManager.log(lastDBLocation);
				onLocalFinish(true);
			} else {
				if (null != location) {
					showToast("定位失败，请重试! 错误码:" + location.getLocType());
				}
				onLocalFinish(false);
			}
		}
	};

	public void onDestroy() {
		LocationManager.getInstance().unregisterlistener(mListener);
		super.onDestroy();
	};

	@Override
	public int getLayoutId() {
		return R.layout.attendance_main;
	}

	@OnClick(R.id.back)
	public void onclickBack() {
		getActivity().finish();
	}

	@OnClick(R.id.right_text)
	public void onclickRight() {
		Intent intent = new Intent(mContext, AttendanceHistoryActivity.class);
		startActivity(intent);
	}

	@Override
	protected boolean hasEventLife() {
		return true;
	}

}
